package com.zlp.spring.one.service;

import com.zlp.spring.one.annotation.BeanPostProcessor;
import com.zlp.spring.one.annotation.Component;
import com.zlp.spring.one.service.impl.OrderServiceImpl;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.Method;
import java.util.Objects;

@Component
public class ZlpBeanPostProcessor implements BeanPostProcessor {


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

//        if (Objects.equals(beanName,"orderService")) {
//            System.out.println("初始化前");
//            OrderServiceImpl orderService = (OrderServiceImpl) bean;
//            orderService.setName("bfdsfds");
//            return orderService;
//        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {

        System.out.println("初始化后");
        if (Objects.equals(beanName,"orderService")) {
            Object proxyInstance = Proxy.newProxyInstance(ZlpBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                    System.out.println("执行代理逻辑==>time"+System.currentTimeMillis());
                    return method.invoke(bean,args);
                }
            });
            return proxyInstance;
        }
        return bean;
    }
}
